package com.ccc.service.impl;

import com.ccc.entity.LoginUser;
import com.ccc.entity.User;
import com.ccc.service.LoginService;
import com.ccc.utils.JwtUtil;
import com.ccc.utils.RedisCache;
import com.ccc.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(User user) {
        // AuthenticationManager 进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 如果认证没通过，给出对应的提示
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        // 如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String username = loginUser.getUser().getUsername().toString();
        String type = loginUser.getUser().getType();
        String jwt = JwtUtil.createJWT(username);

        // 把完整的用户信息存入redis
        redisCache.setCacheObject("Login:" + username, loginUser);

        //把token响应给前端
        Map<String, String> map = new HashMap<>();
        map.put("token", jwt);
        if (type.equals("student"))
            return new ResponseResult(200, type + " Login success!", map);
        else
            return new ResponseResult(201, type + " Login success!", map);
    }

    @Override
    public ResponseResult logout() {
        // 获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String username = loginUser.getUser().getUsername();

        // 删除redis中的值
        redisCache.deleteObject("Login:" + username);
        return new ResponseResult(200, "Logout success");
    }
}
